package ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


public class EhCacheManager {

    private static CacheManager ehCacheManager = null;

  
    public static Object get(CacheRegion regionName, CacheKey cacheKey) {
        Cache cache = getContextCache(regionName);
        if (cache != null && cacheKey != null && cache.get(cacheKey.getValue()) != null){
        	return cache.get(cacheKey.getValue()).getObjectValue();
        }
        return null;
    }

    
    public static void put(CacheRegion regionName, CacheKey cacheKey, Object value) {
        if (value != null) {
            Cache cache = getContextCache(regionName);
            cache.put(new Element(cacheKey.getValue(), value));
        }
    }
    
    public static void remove(CacheRegion regionName, CacheKey cacheKey) {
        net.sf.ehcache.Cache cache = getContextCache(regionName);
        cache.remove(cacheKey.getValue());
    }

    public static net.sf.ehcache.Cache getContextCache(CacheRegion regionName) {
        if (regionName == null) {
            regionName = CacheRegion.DEFAULT;
        }
        return getCacheManager().getCache(regionName.getValue());
    }

  
    private static CacheManager getCacheManager() {
        if (ehCacheManager == null) {
            ehCacheManager = CacheManager.create("src/ehcache/ehcache.xml");
        }
        return ehCacheManager;
    }

    /**
     * test
     *
     */
    public static void main(String[] args) {
    	// put test data
    	EhCacheManager.put(CacheRegion.DEFAULT, CacheKey.CACHE_KEY1, "test");
    	// get data
    	String value = (String) EhCacheManager.get(CacheRegion.DEFAULT, CacheKey.CACHE_KEY1);
    	System.out.println("value = "+value);
	}
}
